package com.esreport.service.impl;

import com.esreport.Utils.BaseGuavaCache;
import com.esreport.Utils.DateUtils;
import com.esreport.Utils.HttpSessionUtils;
import com.esreport.dto.Site;
import com.esreport.service.SiteService;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SiteServiceImpl
 * @Description TODO
 * @Author fanxingwei
 * @Date 2020/5/6 14:07
 * @Version 1.0
 */
@SuppressWarnings("unchecked")
@Transactional(rollbackFor = Exception.class)
@Service
@Slf4j
@Configuration
public class SiteServiceImpl extends BaseGuavaCache implements SiteService {

    @Value("${api.site.list:#{null}}")
    public String siteUrl;
    @Value("${api.site.info:#{null}}")
    public String siteInfo;
    @Value("${api.site.cache_refresh_sec:#{null}}")
    public Integer siteCacheRefresh;

    @Override
    public List<Site> list() {
        List<Site> acctSites = new ArrayList<>(128);

        // 获取信息
        String info = null;
        try {
            info = HttpSessionUtils.httpGet(HttpSessionUtils.buildHttpClient(), siteUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (info == null || "".equals(info)) {
            return (List<Site>) this.getValue("all");
        }

        JsonParser parser = new JsonParser();
        JsonObject infoObject = (JsonObject) parser.parse(info);

        if (infoObject.get("data") != null && !(("null").equals(infoObject.get("data").toString()) && !"".equals((infoObject.get("data").toString())))) {
            JsonArray data = infoObject.get("data").getAsJsonArray();
            for (JsonElement jsonElement : data) {
                Site acctSite = new Site();
                acctSite.setId(jsonElement.getAsJsonObject().get("id").getAsString());
                acctSite.setSiteId(jsonElement.getAsJsonObject().get("siteId").getAsInt());
                acctSite.setSiteName(jsonElement.getAsJsonObject().get("siteName").getAsString());
                acctSite.setUpdateTime(DateUtils.parseDate(jsonElement.getAsJsonObject().get("updateTime").getAsString(), "yyyy/MM/DD HH:mm:ss"));
                acctSites.add(acctSite);
                if (System.currentTimeMillis() - Long.parseLong(this.getValue("updateTime").toString()) > 1000 * siteCacheRefresh) {
                    this.put(jsonElement.getAsJsonObject().get("siteId").getAsInt(), acctSite);
                }
            }
            if (System.currentTimeMillis() - Long.parseLong(this.getValue("updateTime").toString()) > 1000 * siteCacheRefresh) {
                this.put("all", acctSites);
                this.put("updateTime", System.currentTimeMillis());
                log.info("站点缓存已成功刷新！");
            }
        }
        return acctSites;
    }

    @Override
    public Site findBySiteId(Integer siteId) {
        Site acctSite = null;
        // 获取信息
        String info = null;
        try {
            info = HttpSessionUtils.httpGet(HttpSessionUtils.buildHttpClient(), siteInfo + "?siteId=" + siteId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (info == null || "".equals(info)) {
            if (this.getValue(siteId) instanceof Site) {
                return (Site) this.getValue(siteId);
            } else {
                return null;
            }
        }

        JsonParser parser = new JsonParser();
        JsonObject infoObject = (JsonObject) parser.parse(info);

        if (infoObject.get("data") != null && !("null").equals(infoObject.get("data").toString()) && !"".equals((infoObject.get("data").toString()))) {
            JsonObject data = infoObject.get("data").getAsJsonObject();
            acctSite = new Site();
            acctSite.setId(data.get("id").getAsString());
            acctSite.setSiteId(data.get("siteId").getAsInt());
            acctSite.setSiteName(data.get("siteName").getAsString());
            acctSite.setUpdateTime(DateUtils.parseDate(data.get("updateTime").getAsString(), "yyyy/MM/DD HH:mm:ss"));
        }

        return acctSite;
    }

    @Override
    protected Object getValueWhenExpired(Object key) throws Exception {
        return "0";
    }

}
